package io.renren.service.impl;

import cn.hutool.db.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import dm.jdbc.util.StringUtil;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.service.impl.CrudServiceImpl;
import io.renren.common.utils.DateUtils;
import io.renren.dao.*;
import io.renren.dto.*;
import io.renren.entity.*;
import io.renren.service.AutorepairmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ${comments}
 *
 * @author Sen 524227263@qq.com
 * @since 1.0.0 2024-05-28
 */
@Service
public class AutorepairmServiceImpl extends CrudServiceImpl<AutorepairmDao, AutorepairmEntity, AutorepairmDTO> implements AutorepairmService {

    @Autowired
    private AutorepairmDao autorepairmDao;
    @Autowired
    private AutodecoratemDao autorecoratemDao;
    @Autowired
    private AutowashmDao autowashmDao;
    @Autowired
    private AutorescuemDao autorescuemDao;
    @Autowired
    private AgencyinsuranceregmDao agencyinsuranceregmDao;
    @Autowired
    private JoinmembermDao joinmembermDao;
    @Autowired
    private AutoservicemDao autoservicemDao;
    @Autowired
    private DocdataDao docdataDao;
    @Autowired
    private AutorepairmDao autorerepairmDao;

    @Override
    public QueryWrapper<AutorepairmEntity> getWrapper(Map<String, Object> params) {
        String id = (String) params.get("id");

        QueryWrapper<AutorepairmEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(id), "id", id);

        return wrapper;
    }


    @Override
    public Map<String, Object> myAutoServiceList(String traderMOID, String autoOID, Integer pageCount, Integer pageSize) {


        //分页
        //        Long count1 = autorepairmDao.selectCount(new QueryWrapper<AutorepairmEntity>().eq("Auto_FK", autoOID));
        //        Long count2 = autorecoratemDao.selectCount(new QueryWrapper<AutodecoratemEntity>().eq("Auto_FK", autoOID));
        //        Long count3 = autowashmDao.selectCount(new QueryWrapper<AutowashmEntity>().eq("Auto_FK", autoOID));
        //        Long count4 = autorescuemDao.selectCount(new QueryWrapper<AutorescuemEntity>().eq("Auto_FK", autoOID));
        //        Long count5 = agencyinsuranceregmDao.selectCount(new QueryWrapper<AgencyinsuranceregmEntity>().eq("Auto_FK", autoOID));
        //        Long count6 = joinmembermDao.selectCount(new QueryWrapper<JoinmembermEntity>().eq("Auto_FK", autoOID));
        //        Long count7 = autoservicemDao.selectCount(new QueryWrapper<AutoservicemEntity>().eq("Auto_FK", autoOID));

        List<Map<String, Object>> listExSql = autorepairmDao.selectListExSql(autoOID);
        int indexNo = 1;
        for (Map<String, Object> map : listExSql) {
            map.put("ROW_NUMBER", indexNo + "");
            indexNo++;
        }
        Map<String, Object> result = new HashMap<>();
        result.put("data", listExSql);
        result.put("total", listExSql.size());
        result.put("current_page", 1);
        result.put("per_page", listExSql.size());
        return result;
    }

    @Override
    public Map<String, Object> serviceProgress(String traderMOID, BusinessKeyDto dto) {
        Map<String, Object> result = new HashMap<>();

        List<Map<String, Object>> autorepairmMapList = autorepairmDao
                .selectMaps(new QueryWrapper<AutorepairmEntity>()
                        .select("FaultDescription,CheckRepairSituation,SYS_Created")
                        .eq("AutoRepairMOID", dto.getBusinessKey()));
        if (autorepairmMapList.size() > 0) {
            Map<String, Object> entryCondition = autorepairmMapList.get(0);

            List<DocdataEntity> docdataList = docdataDao
                    .selectList(new QueryWrapper<DocdataEntity>()
                            .select("FileName,DOCDesc")
                            .eq("BusinessKey", dto.getBusinessKey()));
            entryCondition.put("imgs", docdataList);
            result.put("entryCondition", entryCondition);

            // 车辆检测
            AutorepairmEntity autorepairmEntity = autorerepairmDao
                    .selectOne(new QueryWrapper<AutorepairmEntity>()
                            .select("RoutineTestDate,RoutineTestRemark")
                            .eq("AutoRepairMOID", dto.getBusinessKey()));
            Map<String, Object> checkInfo = new HashMap<>();
            if (autorepairmEntity != null) {
                checkInfo.put("RoutineTestDate", autorepairmEntity.getRoutinetestdate());
                checkInfo.put("RoutineTestRemark", autorepairmEntity.getRoutinetestremark());
            }else {
                checkInfo.put("RoutineTestDate", "");
                checkInfo.put("RoutineTestRemark", "");
            }
            List<Map<String, Object>> autoRepairItems = autorerepairmDao.getAutoRepairItems(dto.getBusinessKey());

            //            for (Map<String, Object> map : autoRepairItems){
            //                if (map.get("QualifiedTime") != null) {
            //                    map.put("QualifiedTime", autoRepairItems.get(0).get("QualifiedTime"));
            //                    map.put("SYS_Created", autoRepairItems.get(0).get("SYS_Created"));
            //                    map.put("Name", autoRepairItems.get(0).get("Name"));
            //                    map.put("QualifiedResult", autoRepairItems.get(0).get("QualifiedResult"));
            //                }
            //            }


            //            if (autoRepairItems.size() > 0 && autoRepairItems.get(0).get("QualifiedTime") != null) {
            //                autoRepairItem.put("QualifiedTime", autoRepairItems.get(0).get("QualifiedTime"));
            //                autoRepairItem.put("SYS_Created", autoRepairItems.get(0).get("SYS_Created"));
            //                autoRepairItem.put("Name", autoRepairItems.get(0).get("Name"));
            //                autoRepairItem.put("QualifiedResult", autoRepairItems.get(0).get("QualifiedResult"));
            //            } else {
            //                autoRepairItem.put("QualifiedTime", "");
            //                autoRepairItem.put("SYS_Created", "");
            //                autoRepairItem.put("Name", "");
            //                autoRepairItem.put("QualifiedResult", "");
            //            }

            checkInfo.put("checkDetail", autoRepairItems);
            result.put("checkInfo", checkInfo);

            List<String> qualifiedTimes = autorerepairmDao.getQualifiedTimeList(dto.getBusinessKey());
            if (qualifiedTimes.size() > 0 && !qualifiedTimes.get(0).equals("1900-01-01 00:00:00.0")) {
                result.put("QualifiedTime", qualifiedTimes.get(0));
            } else {
                result.put("QualifiedTime", "");
            }
            // 验收
            AutorepairmEntity autorepairmYanShou = autorerepairmDao.selectOne(new QueryWrapper<AutorepairmEntity>().select("CaseCloseDate").eq("AutoRepairMOID", dto.getBusinessKey()).apply("CaseCloseDate is not null"));
            if (autorepairmYanShou != null && autorepairmYanShou.getCaseclosedate() != null) {
                String caseclosedateStr = DateUtils.format(autorepairmYanShou.getCaseclosedate(), "yyyy-MM-dd HH:mm:sss");
                if (!caseclosedateStr.equals("1900-01-01 00:00:00.000")) {
                    result.put("CaseCloseDate", caseclosedateStr);
                } else {
                    result.put("CaseCloseDate", "");
                }
            } else {
                result.put("CaseCloseDate", "");
            }
            // 洗车
            List<Map<String, Object>> washDateMap = autorerepairmDao.getwashDateMap(dto.getBusinessKey());
            if (washDateMap.size() > 0) {
                result.put("washDate", DateUtils.parse(washDateMap.get(0).toString(), "yyyy-MM-dd HH:mm:ss"));
            } else {
                result.put("washDate", "");
            }
            // 结算
            List<Map<String, Object>> jiesuanMap = autorerepairmDao.getjiesuanMap(dto.getBusinessKey());
            if (jiesuanMap.size() > 0) {
                result.put("settlementDate", DateUtils.parse(jiesuanMap.get(0).get("SYS_Created").toString(), "yyyy-MM-dd HH:mm:ss"));
            } else {
                result.put("settlementDate", "");
            }

        }
        return result;
    }

    @Autowired
    private UnitsDao unitsDao;

    @Autowired
    private UcmlOrganizeDao ucmlOrganizeDao;
    @Autowired
    private UcmlContactDao ucmlContactDao;

    @Override
    public Map<String, Object> autoRepairDetail(String traderMOID, RepairDetailDto dto) {
        Map<String, Object> result = new HashMap<>();
        AutorepairmEntity info = baseDao.selectOne(new QueryWrapper<AutorepairmEntity>().eq("AutoRepairMOID", dto.getAutoRepairMoId()));
        if (info != null) {
            List<Map<String, Object>> technicianInfo = baseDao.getTechnicianInfo(dto.getAutoRepairMoId());

            List<Map<String, Object>> goodsList = baseDao.getgoodsList(dto.getAutoRepairMoId());
            for (Map<String, Object> map : goodsList) {
                map.put("BusinessQuantity", new BigDecimal(map.get("BusinessQuantity").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                map.put("Amount", new BigDecimal(map.get("Amount").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                map.put("BusinessAmount", new BigDecimal(map.get("BusinessAmount").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                UnitsEntity unitsEntity = unitsDao.selectOne(new QueryWrapper<UnitsEntity>().select("Name").eq("UnitsOID", map.get("Units_FK")));
                if (unitsEntity != null) {
                    map.put("unitName", unitsEntity.getName());
                }
            }
            result.put("GiveRepairTraderName", info.getGiverepairtradername());
            result.put("GiveRepairTel", info.getTel());
            result.put("technicianName", technicianInfo.size() > 0 ? technicianInfo.get(0).get("PersonName") : "");
            result.put("goodsList", goodsList);
            result.put("serviceDate", DateUtils.format(info.getBilldate(), "yyyy-MM-dd HH:mm:ss"));

            // 服务机构
            UcmlOrganizeEntity organizeEntity = ucmlOrganizeDao.selectOne(new QueryWrapper<UcmlOrganizeEntity>()
                    .select("OrgName")
                    .eq("UCML_OrganizeOID", info.getOrgFk()));
            result.put("orgName", organizeEntity != null ? organizeEntity.getOrgname() : "");
            // 接待员
            UcmlContactEntity ucmlContactEntity = ucmlContactDao.selectOne(
                    new QueryWrapper<UcmlContactEntity>().select("PersonName")
                            .eq("UCML_CONTACTOID", info.getUcmlContactFk()));
            result.put("PersonName", ucmlContactEntity != null ? ucmlContactEntity.getPersonname() : "");

            result.put("BusinessAmount", new BigDecimal(info.getRepairtotalamount()).setScale(2, BigDecimal.ROUND_HALF_UP));
            result.put("vipDiscount", info.getRepairtotaldeductamount().setScale(2, BigDecimal.ROUND_HALF_UP));
            result.put("couponDiscount", 0);
            result.put("routineTestRemark", StringUtil.isNotEmpty(info.getRoutinetestremark()) ? info.getRoutinetestremark() : "");
            result.put("Amount", info.getRepairamount().setScale(2, BigDecimal.ROUND_HALF_UP));

            List<Map<String, Object>> projectList = baseDao.getProjuectList(dto.getAutoRepairMoId());
            result.put("projectList", projectList);
        }
        return result;
    }

    @Override
    public Map<String, Object> autoReturnRepairDetail(String traderMOID, ReturnRepairDetailDto dto) {
        Map<String, Object> result = new HashMap<>();
        AutorepairmEntity info = baseDao.selectOne(new QueryWrapper<AutorepairmEntity>().eq("AutoRepairMOID", dto.getAutoRepairMoId()));
        if (info != null) {
            List<Map<String, Object>> technicianInfo = baseDao.getTechnicianInfo(dto.getAutoRepairMoId());
            List<Map<String, Object>> goodsList = baseDao.getgoodsList(dto.getAutoRepairMoId());
            for (Map<String, Object> map : goodsList) {
                map.put("BusinessQuantity", new BigDecimal(map.get("BusinessQuantity").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                map.put("Amount", new BigDecimal(map.get("Amount").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                map.put("BusinessAmount", new BigDecimal(map.get("BusinessAmount").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                UnitsEntity unitsEntity = unitsDao.selectOne(new QueryWrapper<UnitsEntity>().select("Name").eq("UnitsOID", map.get("Units_FK")));
                if (unitsEntity != null) {
                    map.put("unitName", unitsEntity.getName());
                }
            }

            result.put("GiveRepairTraderName", info.getGiverepairtradername());
            result.put("GiveRepairTel", info.getTel());
            result.put("technicianName", technicianInfo.size() > 0 ? technicianInfo.get(0).get("PersonName") : "");
            result.put("goodsList", goodsList);
            result.put("serviceDate", DateUtils.format(info.getBilldate(), "yyyy-MM-dd HH:mm:ss"));

            // 服务机构
            UcmlOrganizeEntity organizeEntity = ucmlOrganizeDao.selectOne(new QueryWrapper<UcmlOrganizeEntity>()
                    .select("OrgName")
                    .eq("UCML_OrganizeOID", info.getOrgFk()));
            result.put("orgName", organizeEntity != null ? organizeEntity.getOrgname() : "");
            // 接待员
            UcmlContactEntity ucmlContactEntity = ucmlContactDao.selectOne(
                    new QueryWrapper<UcmlContactEntity>().select("PersonName")
                            .eq("UCML_CONTACTOID", info.getUcmlContactFk()));
            result.put("PersonName", ucmlContactEntity != null ? ucmlContactEntity.getPersonname() : "");

            result.put("BusinessAmount", new BigDecimal(info.getRepairtotalamount()).setScale(2, BigDecimal.ROUND_HALF_UP));
            result.put("vipDiscount", info.getRepairtotaldeductamount().setScale(2, BigDecimal.ROUND_HALF_UP));
            result.put("couponDiscount", 0);
            result.put("Amount", info.getRepairamount().setScale(2, BigDecimal.ROUND_HALF_UP));

            List<Map<String, Object>> projectList = baseDao.getProjuectList2(dto.getAutoRepairMoId());
            result.put("projectList", projectList);

        }
        return result;
    }

    @Override
    public Map<String, Object> autoBaoYangDetail(String traderMOID, BaoYangDetailDto dto) {
        Map<String, Object> result = new HashMap<>();
        AutorepairmEntity info = baseDao.selectOne(new QueryWrapper<AutorepairmEntity>().eq("AutoRepairMOID", dto.getAutoRepairMoId()));
        if (info != null) {
            List<Map<String, Object>> technicianInfo = baseDao.getTechnicianInfo(dto.getAutoRepairMoId());
            List<Map<String, Object>> goodsList = baseDao.getgoodsList(dto.getAutoRepairMoId());
            for (Map<String, Object> map : goodsList) {
                map.put("BusinessQuantity", new BigDecimal(map.get("BusinessQuantity").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                map.put("Amount", new BigDecimal(map.get("Amount").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                map.put("BusinessAmount", new BigDecimal(map.get("BusinessAmount").toString()).setScale(2, BigDecimal.ROUND_HALF_UP));
                UnitsEntity unitsEntity = unitsDao.selectOne(new QueryWrapper<UnitsEntity>().select("Name").eq("UnitsOID", map.get("Units_FK")));
                if (unitsEntity != null) {
                    map.put("unitName", unitsEntity.getName());
                }
            }

            result.put("GiveRepairTraderName", info.getGiverepairtradername());
            result.put("GiveRepairTel", info.getTel());
            result.put("technicianName", technicianInfo.size() > 0 ? technicianInfo.get(0).get("PersonName") : "");
            result.put("goodsList", goodsList);
            result.put("serviceDate", DateUtils.format(info.getBilldate(), "yyyy-MM-dd HH:mm:ss"));

            // 服务机构
            UcmlOrganizeEntity organizeEntity = ucmlOrganizeDao.selectOne(new QueryWrapper<UcmlOrganizeEntity>()
                    .select("OrgName")
                    .eq("UCML_OrganizeOID", info.getOrgFk()));
            result.put("orgName", organizeEntity != null ? organizeEntity.getOrgname() : "");
            // 接待员
            UcmlContactEntity ucmlContactEntity = ucmlContactDao.selectOne(
                    new QueryWrapper<UcmlContactEntity>().select("PersonName")
                            .eq("UCML_CONTACTOID", info.getUcmlContactFk()));
            result.put("PersonName", ucmlContactEntity != null ? ucmlContactEntity.getPersonname() : "");

            result.put("BusinessAmount", new BigDecimal(info.getRepairtotalamount()).setScale(2, BigDecimal.ROUND_HALF_UP));
            result.put("vipDiscount", info.getRepairtotaldeductamount().setScale(2, BigDecimal.ROUND_HALF_UP));
            result.put("couponDiscount", 0);
            result.put("Amount", info.getRepairamount().setScale(2, BigDecimal.ROUND_HALF_UP));

            List<Map<String, Object>> projectList = baseDao.getProjuectList2(dto.getAutoRepairMoId());
            result.put("projectList", projectList);
        }
        return result;
    }

    @Override
    public AutorepairmEntity findInfoById(String sourceBillOID) {
        QueryWrapper<AutorepairmEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(StrUtil.isNotBlank(sourceBillOID), "AutoRepairMOID", sourceBillOID);
        return baseDao.selectOne(wrapper);
    }
}